package cat.joronya.supermanager.service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashSet;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import cat.joronya.supermanager.Supermanager;

public class NextMatchesSync 
{
	// el service
	private SupermanagerService service;
		
	// day matches GET
	private static final String NEXTMATCHES_GET = "http://www.acb.com/proxjornadas.php";
	
	// el client http on fer les peticions
	private DefaultHttpClient client = null;
	
	// hash per guardar team vs team
	protected ArrayList<ContentValues> nextMatches = null;
	
	// hashset per guardar els dies parsejats
	protected HashSet<Integer> days = null;
	
	public NextMatchesSync(SupermanagerService service, DefaultHttpClient client)
	{
		this.service = service;
		this.client = client;
	}
	
	/**
	 * Sync day matches from ACB web, no need for session.
	 */
	public void sync()
	{
		try
		{
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();

			if( !online )
				throw new ConnectivityException();
			
			parse();
			
			persist();
		}
		catch(Exception e){
			Log.d(Supermanager.TAG, "Error sync next matches: "+e.getMessage());
		}
	}
	
	private void parse() throws Exception
	{
		HttpGet plHttpGet = new HttpGet(NEXTMATCHES_GET);
		HttpResponse response = client.execute(plHttpGet);

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String nextMatchesPage = os.toString(HTTP.ISO_8859_1);

		NextMatchesParser parser = NextMatchesParserProvider.getImpl(Package.getPackage("cat.joronya.supermanager.service.substrImpl"));
		Log.d(Supermanager.TAG, "Start parsing next matches page...");
		long elapsedTime = parser.parse(nextMatchesPage);
		Log.d(Supermanager.TAG, "Stop parsing next matches page! Elapsed time: "+elapsedTime/1000);

		nextMatches = parser.getNextMatches();
		days = parser.getDayMatches();
	}
	
	private void persist() throws Exception
	{
		// borrem entrades existents de les jornades parsejades
		for(Integer day: days)
		{
			int ret = service.getContentResolver().delete(Supermanager.NextMatches.CONTENT_URI,
				Supermanager.NextMatches.DAY + " = ? ", 
				new String[]{day.toString()});
			Log.d(Supermanager.TAG, "deleted next matches: "+ret);
		}
		
		// inserim noves linies
		ContentValues[] values = new ContentValues[nextMatches.size()];
		values = nextMatches.toArray(values);
		service.getContentResolver().bulkInsert(Supermanager.NextMatches.CONTENT_URI, values);
	}
	
	public ArrayList<ContentValues> getNextMatches()
	{
		return nextMatches;
	}
}
